import * as crypto from "node:crypto";

export class AesUtil {
    static encrypt(plaintext, base64Key) {
        if (!base64Key) {
            throw new Error('Key cannot be null or empty');
        }

        // 将Base64密钥解码为字节
        const key = Buffer.from(base64Key, 'base64');

        // 验证密钥长度是否为32字节
        if (key.length !== 32) {
            throw new Error(`Invalid key length. Expected 32 bytes but got ${key.length} bytes. Please ensure the key is generated correctly.`);
        }

        // 创建16字节的随机IV
        const iv = crypto.randomBytes(16);

        // 使用解码后的密钥创建cipher
        const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);

        // 加密数据
        let encrypted = cipher.update(plaintext, 'utf8', 'base64');
        encrypted += cipher.final('base64');

        // 返回 IV:加密数据 的格式
        return iv.toString('base64') + ':' + encrypted;
    }

    static decrypt(encryptedText, base64Key) {
        if (!encryptedText || !base64Key) {
            throw new Error('Encrypted text and key cannot be null or empty');
        }

        // 将Base64密钥解码为字节
        const key = Buffer.from(base64Key, 'base64');

        // 验证密钥长度
        if (key.length !== 32) {
            throw new Error(`Invalid key length. Expected 32 bytes but got ${key.length} bytes. Please ensure the key is generated correctly.`);
        }

        // 从加密文本中分离出IV和加密数据
        const [ivBase64, encryptedBase64] = encryptedText.split(':');

        // 解码IV
        const iv = Buffer.from(ivBase64, 'base64');

        // 创建解密器
        const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);

        // 解密数据
        let decrypted = decipher.update(encryptedBase64, 'base64', 'utf8');
        decrypted += decipher.final('utf8');

        return decrypted;
    }
}